package com.camartsApp.controller;

import com.camartsApp.Util.RedisUtil;
import com.camartsApp.Util.Response;
import com.camartsApp.common.ResultVO;
import com.camartsApp.dto.TopUserWithPhotoDTO;
import com.camartsApp.service.TopUserService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/top-users")
public class TopUserController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private TopUserService topUserService;

    private static final String TOP_USER_CACHE_KEY = "cache:topUsersWithPhoto";

    private final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());

    /**
     * 获取达人榜，包含点赞最高作品，支持缓存
     */
    @GetMapping("/withTopPhoto")
    public ResultVO getTopUsersWithTopPhoto(@RequestParam(defaultValue = "20") int limit) {
        try {
            // 先从缓存取
            String json = redisUtil.get(TOP_USER_CACHE_KEY);
            if (json != null && !json.isEmpty()) {
                List<TopUserWithPhotoDTO> dtoList = objectMapper.readValue(json, new TypeReference<List<TopUserWithPhotoDTO>>() {});
                return Response.OkByDataAndMsg(dtoList, "获取缓存达人榜成功");
            }

            // 缓存无数据，查询数据库
            List<TopUserWithPhotoDTO> dtoList = topUserService.getTopUsersWithTopPhoto(limit);

            // 缓存，设置过期时间1小时
            String newJson = objectMapper.writeValueAsString(dtoList);
            redisUtil.set(TOP_USER_CACHE_KEY, newJson, 100);

            return Response.OkByDataAndMsg(dtoList, "缓存不存在，已实时查询并缓存达人榜");
        } catch (Exception e) {
            return Response.FailResultByMsg("获取达人榜失败：" + e.getMessage());
        }
    }
}
